import subprocess
import configparser
from core_oms import core_oms
from flask import request
from anytools.log_part import log_init
import logging
import json
import re

@core_oms.route('/recure', methods=["GET", "POST"])
def app_recure():
    alarm_info = str(request.data, encoding="utf-8")
    alarm_info = json.loads(alarm_info)
    log_init("app_start.log") # 日志部分
    for alarm_detail in alarm_info['detail']:
        # core应用
        if 'service' in alarm_detail['tags'] and "core" in alarm_detail['tags']['service']:
            # 获取一些信息:应用名字、主机ip，生成启动脚本路径、启动用户名
            ip = alarm_info['endpoint']
            appname = alarm_detail['tags']['service']
            appname = appname.split('-')[0]
            start_route = '/data/app/smy-' + appname + '/jetty/' + appname + '-core/bin/'
            appname = 'smy-' + appname
            
            logging.info('CORE 机器{0}的{1}意外停止，现在开始自动拉起'.format(ip, appname))
            # 使用subprocess模块调用ansible命令启动应用  host的路径需要注意
            subprocess.getstatusoutput('grep -ri {0} /data/app/recure/host_recure; if [ $? -ne 0 ];then echo {0} >> /data/app/recure/host_recure; fi'.format(ip))
            start_status, start_out = subprocess.getstatusoutput('ansible-playbook -i /data/app/recure/host_recure -l {0} /data/app/recure/core_oms/app_recure.yaml -e appname="{1}" -e app_route="{2}" -t core_start'.format(ip, appname, start_route))
            # 验证应用是否启动成功
            status, out = subprocess.getstatusoutput('ansible -i /data/app/recure/host_recure {0} -m shell -a "ps -ef|grep {1}|grep Djava|grep -v grep"'.format(ip, appname)) 
            if status == 0:
                logging.info('CORE 机器{0}的{1}启动成功'.format(ip, appname))
            else:
                logging.warning('CORE 机器{0}的{1}启动失败，信息如下:\n{2}'.format(ip, appname, start_out))


        # oms应用
        elif 'service' in alarm_detail['tags'] and "apache-tomcat-9.0.31" in alarm_detail['tags']['target']:
            ip = alarm_info['endpoint']
            appname = alarm_detail['tags']['service']
            start_route = '/data/app/smy-' + appname + '/tomcat/'
            appname = 'smy-' + appname
            
            logging.info("OMS 机器{0}的{1}意外停止，现在开始自动拉起".format(ip, appname))
            subprocess.getstatusoutput('grep -ri {0} /data/app/recure/host_recure; if [ $? -ne 0 ];then echo {0} >> /data/app/recure/host_recure; fi'.format(ip))
            start_status, start_out = subprocess.getstatusoutput('ansible-playbook -i /data/app/recure/host_recure -l {0} /data/app/recure/core_oms/app_recure.yaml -e appname="{1}" -e app_route="{2}" -t oms_start'.format(ip, appname, start_route))
            # 验证应用是否启动成功
            status, out = subprocess.getstatusoutput('ansible -i /data/app/recure/host_recure {0} -m shell -a "ps -ef|grep "{1}"|grep apache-tomcat|grep -v grep"'.format(ip, appname))
            if status == 0:
                logging.info('OMS 机器{0}的{1}启动成功'.format(ip, appname))
            else:
                logging.warning('OMS 机器{0}的{1}启动失败，信息如下:\n{2}'.format(ip, appname, start_out))


        # node应用
        elif alarm_detail['metric'] and alarm_detail['metric'] == 'nodejs.proc.num':
            ip = alarm_info['endpoint']
            start_route = '/data/app/node/node/'
            stop_route = '/data/app/node/node/stop.sh'
            
            logging.info("NODE 机器{0}的node意外停止，现在开始自动拉起".format(ip))
            subprocess.getstatusoutput('grep -ri {0} /data/app/recure/host_recure; if [ $? -ne 0 ];then echo {0} >> /data/app/recure/host_recure; fi'.format(ip))
            start_status, start_out = subprocess.getstatusoutput('ansible-playbook -i /data/app/recure/host_recure -l {0} /data/app/recure/core_oms/app_recure.yaml -e app_route="{1}" -t nodejs_start'.format(ip, start_route))
            # 验证应用是否启动成功
            status, out = subprocess.getstatusoutput('ansible -i /data/app/recure/host_recure {0} -m shell -a "ps -ef|grep node_modules|grep smy-wxs|grep -v grep"'.format(ip))
            if status == 0:
                logging.info('OMS 机器{0}的node启动成功'.format(ip))
            else:
                logging.warning('OMS 机器{0}的node启动失败，信息如下:\n{1}'.format(ip, start_out))
            
    return 'ok'


@core_oms.route('/middleware', methods=['GET', 'POST'])
def middl_recure():
    log_init("app_start.log") # 日志部分
    alarm_info = str(request.data, encoding="utf-8")
    alarm_info = json.loads(alarm_info)
    # print(alarm_info)
    ip = alarm_info['endpoint']
    for alarm_detail in alarm_info['detail']:
        service = alarm_detail['tags']['service']
        # 读取配置信息
        config = configparser.ConfigParser()
        config.read('/data/app/recure/core_oms/recure.ini')
        config_info = config[service]
        start_route = config_info['start_route']
        judge_tag = config_info['judge_tag']
        start_cmd = config_info['start_cmd']
        user = config_info['user']

        # 启动
        logging.info("APP 机器{0}的{1}意外停止，现在开始自动拉起".format(ip, service))
        subprocess.getstatusoutput('grep -ri {0} /data/app/recure/host_recure; if [ $? -ne 0 ];then echo {0} >> /data/app/recure/host_recure; fi'.format(ip))
        start_status, start_out = subprocess.getstatusoutput('ansible-playbook -i /data/app/recure/host_recure -l {0} /data/app/recure/core_oms/app_recure.yaml -e start_cmd="{1}" -e app_route="{2}" -e user="{3}" -t app_recure'.format(ip, start_cmd, start_route, user))
        status, out = subprocess.getstatusoutput('ansible -i /data/app/recure/host_recure {0} -m shell -a "ps -ef|grep "{1}"|grep -v grep"'.format(ip, judge_tag))        
        if status == 0:
            logging.info('APP 机器{0}的{1}启动成功'.format(ip, service))
        else:
            logging.warning('APP 机器{0}的{1}启动失败，信息如下:\n{2}'.format(ip, service, start_out))
    return 'ok'


